﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;
using System.Data.Common;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace MINERP.DAL.DigitalOutput
{
    public class DigitalOutPutDAL : DALBase
    {
        //string conStr = ConfigurationManager.ConnectionStrings["fffff"].ToString();
        string conStr = DALBase.ConnStr;
        SqlConnection con = new SqlConnection();

        #region 获取照片信息集合(传统模式稳定后删除)
        /// <summary> 获取未分配打印机照片信息集合
        /// 获取照片信息集合
        /// </summary>
        public ObjectQuery<DbDataRecord> GetPhotoList2(int NoDistributedPrinter, int techId, int usingStatus, int usingStatus2)
        {
            try
            {
                //1
                int orderInfoStatus = (int)COM.OrderInfoStatus.Doing;
                StringBuilder esql2 = new StringBuilder();
                esql2.Append("select it.photoID,it.PhotoBarCode,it.PrinterId,it.paperType.Name as PaperTypeName,it.paperFace.Name as PaperFaceName,it.orderInfo.Tb_OrderBag.Shop.ShopName,Shop.Area,it.orderInfo.CtmName");
                esql2.Append(",it.Width as SizeWidth,it.Height as SizeHeight,it.PixWidth,it.PixHeight,it.orderInfo.OrderProductCode,it.orderInfo.ProductType,it.orderInfo.Tb_OrderBag.BagCode as OrderBagCode,it.orderInfo.Tb_OrderBag.OrderTime,it.orderInfo.Tb_OrderBag.FetchTime ");
                esql2.Append(",it.orderInfo.Tb_OrderBag.OrderBagId,it.orderInfo.Tb_OrderBag.BagName as OrderName,it.orderInfo.Priority as OrderPriority,it.orderInfo.OrderProductId,it.orderInfo.OrderProductName");
                esql2.Append(" from photoInfo as it where it.status=@NoDistributedPrinter and it.orderInfo.status=" + orderInfoStatus + " and it.orderInfo.OrderProductId in (select value itt.orderInfo.OrderProductId from WorkOrderFlowList as itt where itt.tb_Tech.TechId=@techId and (itt.Status=@usingStatus or itt.status=@usingStatus2))");
                ObjectQuery<DbDataRecord> query = DataEntites.CreateQuery<DbDataRecord>(esql2.ToString(), new ObjectParameter("NoDistributedPrinter", NoDistributedPrinter), new ObjectParameter("techId", techId), new ObjectParameter("usingStatus", usingStatus), new ObjectParameter("usingStatus2", usingStatus2));
                return query;
            }
            catch (Exception ex)
            {
                DataEntites.Refresh(RefreshMode.StoreWins, DataEntites.photoInfo);
                throw ex;
            }
        }
        public DataTable GetPhotoList(int NoDistributedPrinter, int techId, int usingStatus, int usingStatus2)
        {
            using (con = new SqlConnection(conStr))
            {
                try
                {
                    int orderInfoStatus = (int)COM.OrderInfoStatus.Doing;
                    StringBuilder sql = new StringBuilder();
                    sql.Append("select photoID,PhotoBarCode,PrinterId,paperType.Name as PaperTypeName,paperFace.Name as PaperFaceName,Shop.ShopName,Shop.Area,orderInfo.CtmName");
                    sql.Append(",photoinfo.Width as SizeWidth,photoinfo.Height as SizeHeight,PixWidth,PixHeight,orderInfo.OrderProductCode,orderInfo.ProductType,Tb_OrderBag.BagCode as OrderBagCode,Tb_OrderBag.OrderTime,Tb_OrderBag.FetchTime ");
                    sql.Append(",Tb_OrderBag.OrderBagId,Tb_OrderBag.BagName as OrderName,orderinfo.Priority as OrderPriority,orderInfo.OrderProductId,orderInfo.OrderProductName,photoinfo.Remark Remark");
                    sql.Append(" from photoInfo inner join paperType on photoinfo.papertypeid=papertype.papertypeid");
                    sql.Append(" inner join paperface on photoinfo.paperfaceid=paperface.paperfaceid");
                    sql.Append(" inner join orderinfo on photoinfo.orderproductid=orderinfo.orderproductid");
                    sql.Append(" inner join tb_orderbag on orderinfo.orderbagid=tb_orderbag.orderbagid");
                    sql.Append(" inner join shop on tb_orderbag.shopid=shop.shopid");
                    sql.Append(" where photoinfo.status=" + NoDistributedPrinter + " and orderinfo.status=" + orderInfoStatus + " and orderinfo.orderproductid in ");
                    sql.Append(" (select orderproductid from workorderflowlist where techid=" + techId + " and status in (" + usingStatus + "," + usingStatus2 + "))");
                    SqlCommand cmd = new SqlCommand(sql.ToString(), con);
                    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                    DataTable dt = new DataTable();
                    con.Open();
                    adapter.Fill(dt);
                    return dt;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
        #endregion

        #region 获取照片信息集合(传统模式稳定后删除)
        /// <summary> 获取未分配打印机照片信息集合
        /// 获取照片信息集合
        /// </summary>
        public ObjectQuery<DbDataRecord> GetPhotoListForChange2(int DistributedPrinter, int printerId)
        {
            try
            {
                //string esql = "select it.photoID,it.PhotoBarCode,it.tb_subOrder.tb_PaperType.PaperTypeName,it.tb_subOrder.tb_PaperFace.PaperFaceName,it.tb_subOrder.tb_OrderDetail.tb_Order.tb_Shop.ShopName,it.tb_subOrder.tb_OrderDetail.tb_Order.tb_Customer.CtmName";
                //esql += ",it.SizeWidth,it.SizeHeight,it.PixWidth,it.PixHeight,it.tb_subOrder.tb_OrderDetail.tb_Order.OrderBagCode,it.tb_subOrder.tb_OrderDetail.BarCode as OrderDetailBarCode,it.tb_subOrder.Barcode as SubOrderBarCode,it.tb_subOrder.tb_OrderDetail.tb_Order.OrderTime,it.tb_subOrder.tb_OrderDetail.tb_Order.FetchTime from tb_photo as it where it.status=@NoDistributedPrinter";
                StringBuilder esql2 = new StringBuilder();
                esql2.Append("select it.photoID,it.PhotoBarCode,it.PrinterId,it.paperType.Name as PaperTypeName,it.paperFace.Name as PaperFaceName,it.orderInfo.Tb_OrderBag.Shop.ShopName,Shop.Area,it.orderInfo.CtmName");
                esql2.Append(",it.Width as SizeWidth,it.Height as SizeHeight,it.PixWidth,it.PixHeight,it.orderInfo.OrderProductCode,it.orderInfo.ProductType,it.orderInfo.Tb_OrderBag.BagCode as OrderBagCode,it.orderInfo.Tb_OrderBag.OrderTime,it.orderInfo.Tb_OrderBag.FetchTime ");
                esql2.Append(",it.orderInfo.Tb_OrderBag.OrderBagId,it.orderInfo.Tb_OrderBag.BagName as OrderName,it.orderInfo.Priority as OrderPriority,it.orderInfo.OrderProductId,it.orderInfo.OrderProductName");
                esql2.Append(" from photoInfo as it where it.status=@NoDistributedPrinter and it.printerId=@printerId");
                ObjectQuery<DbDataRecord> query = DataEntites.CreateQuery<DbDataRecord>(esql2.ToString(), new ObjectParameter("NoDistributedPrinter", DistributedPrinter), new ObjectParameter("printerId", printerId));
                return query;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public DataTable GetPhotoListForChange(int DistributedPrinter, int printerId, int orderInfoStop, int orderBagDel,int inOrderinfoDel)
        {
            using (con = new SqlConnection(conStr))
            {
                try
                {
                    StringBuilder sql = new StringBuilder();
                    sql.Append("select photoID,PhotoBarCode,PrinterId,paperType.Name as PaperTypeName,paperFace.Name as PaperFaceName,Shop.ShopName,Shop.Area,orderInfo.CtmName");
                    sql.Append(",photoinfo.Width as SizeWidth,photoinfo.Height as SizeHeight,PixWidth,PixHeight,orderInfo.OrderProductCode,orderInfo.ProductType,Tb_OrderBag.BagCode as OrderBagCode,Tb_OrderBag.OrderTime,Tb_OrderBag.FetchTime ");
                    sql.Append(",Tb_OrderBag.OrderBagId,Tb_OrderBag.BagName as OrderName,orderinfo.Priority as OrderPriority,orderInfo.OrderProductId,orderInfo.OrderProductName,photoinfo.Remark Remark");
                    sql.Append(" from photoInfo inner join paperType on photoinfo.papertypeid=papertype.papertypeid");
                    sql.Append(" inner join paperface on photoinfo.paperfaceid=paperface.paperfaceid");
                    sql.Append(" inner join orderinfo on photoinfo.orderproductid=orderinfo.orderproductid");
                    sql.Append(" inner join tb_orderbag on orderinfo.orderbagid=tb_orderbag.orderbagid and tb_orderbag.status!=" + orderBagDel);
                    sql.Append(" inner join shop on tb_orderbag.shopid=shop.shopid");
 //                   sql.Append(" where photoinfo.status=" + DistributedPrinter + " and photoinfo.printerId=" + printerId + " and orderinfo.status!=" + orderInfoStop + " and orderinfo.status!=" + inOrderinfoDel);
                    sql.Append(" where photoinfo.status=" + DistributedPrinter + " and photoinfo.printerId=" + printerId + " and orderinfo.status=1");
                    SqlCommand cmd = new SqlCommand(sql.ToString(), con);
                    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                    DataTable dt = new DataTable();
                    con.Open();
                    adapter.Fill(dt);
                    return dt;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
        #endregion

        #region 获取照片信息集合(更新时使用)
        /// <summary>
        /// 获取照片信息集合(更新时使用)
        /// </summary>
        public ObjectQuery<photoInfo> GetPhotoListForUpdate(int NoDistributedPrinter, int techId, int usingStatus, int usingStatus2)
        {
            try
            {
                ObjectQuery<photoInfo> query = DataEntites.photoInfo.Where("it.status=" + NoDistributedPrinter + " and it.orderInfo.OrderProductId in (select value itt.orderInfo.OrderProductId from WorkOrderFlowList as itt where itt.tb_Tech.TechId=" + techId + " and (itt.Status=" + usingStatus + " or itt.Status=" + usingStatus2 + "))").Include("orderInfo").Include("PaperType").Include("PaperFace");
                return query;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 获取照片信息集合(更改打印机时使用)
        /// <summary>
        /// 获取照片信息集合(更改打印机时使用)
        /// </summary>
        public ObjectQuery<photoInfo> GetPhotoListForChangeUpdate(int DistributedPrinter, int printerId)
        {
            try
            {
                ObjectQuery<photoInfo> query = DataEntites.photoInfo.Where("it.status=" + DistributedPrinter + " and it.printerId=" + printerId).Include("orderInfo").Include("PaperType").Include("PaperFace");
                return query;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 获取打印机信息(传统模式稳定后删除)
        /// <summary>
        /// 获取打印机信息
        /// </summary>
        public List<printer> GetPrinterInfo2()
        {
            try
            {
                List<printer> Printers = new List<printer>();
                ObjectQuery<printer> query = DataEntites.printer;
                foreach (printer p in query)
                {
                    Printers.Add(p);
                }
                return Printers;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 获取打印机信息
        /// <summary>
        /// 获取打印机信息
        /// </summary>
        /// <returns></returns>
        public DataTable GetPrinterInfo()
        {
            using (con = new SqlConnection(conStr))
            {
                try
                {
                    string sql = "select PrinterId,PName as PrinterName,PType as PrinterType,PLength,PWidth,PDPI as PrinterDPI,Speed,status3 as IsDisable from printer";
                    SqlCommand cmd = new SqlCommand(sql, con);
                    DataTable dt = new DataTable();
                    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                    con.Open();
                    adapter.Fill(dt);
                    return dt;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
        #endregion

        #region 根据printerID获取本打印机的分配照片数量(传统模式稳定后删除)
        /// <summary>
        /// 根据printerID获取本打印机的分配照片数量
        /// </summary>
        public int GetTaskNumByPrinterID2(int printerID, int DistributedPrinter)
        {
            try
            {
                string esql = "select value count(1) from photoInfo as it where it.PrinterID=@para1 and it.status=@para2";
                int taskNum = DataEntites.CreateQuery<int>(esql, new ObjectParameter[] { new ObjectParameter("para1", printerID), new ObjectParameter("para2", DistributedPrinter) }).First();
                return taskNum;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public int GetTaskNumByPrinterID(int printerID, int DistributedPrinter, int pinbanIng)
        {
            using (con = new SqlConnection(conStr))
            {
                string sql = "select count(photoid) from photoInfo,orderinfo where  photoinfo.orderproductid=orderinfo.orderproductid and orderinfo.status=1 and printerId=" + printerID + " and (photoInfo.status =" + DistributedPrinter + " or photoInfo.status=" + pinbanIng + ")";
                SqlCommand cmd = new SqlCommand(sql, con);
                con.Open();
                return Convert.ToInt32(cmd.ExecuteScalar());
            }
        }
        #endregion

        #region 获取纸型集合(传统模式稳定后删除)
        /// <summary>
        /// 获取纸型集合
        /// </summary>
        public ObjectQuery<string> GetPaperType2()
        {
            try
            {
                string esql = "select value it.Name from paperType as it";
                ObjectQuery<string> query = DataEntites.CreateQuery<string>(esql);
                return query;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public List<string> GetPaperType()
        {
            using (con = new SqlConnection(conStr))
            {
                try
                {
                    string sql = "select Name from paperType";
                    List<string> ps = new List<string>();
                    SqlCommand cmd = new SqlCommand(sql, con);
                    con.Open();
                    SqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        ps.Add(reader["Name"].ToString());
                    }
                    reader.Close();
                    return ps;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
        #endregion

        #region 获取纸面集合(传统模式稳定后删除)
        /// <summary>
        /// 获取纸面集合
        /// </summary>
        public ObjectQuery<string> GetPaperFace2()
        {
            try
            {
                string esql = "select value it.Name from paperFace as it";
                ObjectQuery<string> query = DataEntites.CreateQuery<string>(esql);
                return query;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public List<string> GetPaperFace()
        {
            using (con = new SqlConnection(conStr))
            {
                try
                {
                    string sql = "select Name from paperFace";
                    List<string> ps = new List<string>();
                    SqlCommand cmd = new SqlCommand(sql, con);
                    con.Open();
                    SqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        ps.Add(reader["Name"].ToString());
                    }
                    reader.Close();
                    return ps;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
        #endregion

        #region 获取商户集合(传统模式稳定后删除)
        /// <summary>
        /// 获取商户集合 
        /// </summary>
        public ObjectQuery<DbDataRecord> GetShop2()
        {
            try
            {
                string esql = "select it.ShopID,it.ShopName from Shop as it";
                ObjectQuery<DbDataRecord> query = DataEntites.CreateQuery<DbDataRecord>(esql);
                return query;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public DataTable GetShop()
        {
            using (con = new SqlConnection(conStr))
            {
                try
                {
                    string sql = "select ShopID,ShopName from shop";
                    DataTable dt = new DataTable();
                    SqlCommand cmd = new SqlCommand(sql, con);
                    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                    con.Open();
                    adapter.Fill(dt);
                    return dt;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
        #endregion

        #region 获取指定商户下的客户集合
        /// <summary>
        /// 获取指定商户下的客户集合(有问题)
        /// </summary>
        public ObjectQuery<string> GetCtmByShopID(int shopID)
        {
            try
            {
                string esql = "select value it.CtmName from tb_Customer as it where it.tb_Shop.ShopID=" + shopID;
                ObjectQuery<string> query = DataEntites.CreateQuery<string>(esql);
                return query;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 根据订单ID获取订单信息
        /// <summary>
        /// 根据订单ID获取订单信息
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public Tb_OrderBag GetOrderInfoByOrderId(int orderId)
        {
            try
            {
                Tb_OrderBag order = DataEntites.Tb_OrderBag.Where("it.OrderBagId=" + orderId).Include("Shop").First();
                return order;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 根据OrderBagId获取OrderBag
        /// <summary>
        /// 根据OrderBagId获取OrderBag
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public orderInfo GetOrderInfo(int orderId)
        {
            try
            {
                orderInfo order = DataEntites.orderInfo.Where("it.OrderProductId=" + orderId).First();
                return order;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 刷新照片集合与产品集合
        /// <summary>
        /// 刷新照片集合与产品集合
        /// </summary>
        public void RefreshPhotoAndOrderInfo()
        {
            DataEntites.Refresh(System.Data.Objects.RefreshMode.StoreWins, DataEntites.photoInfo);
            DataEntites.Refresh(System.Data.Objects.RefreshMode.StoreWins, DataEntites.orderInfo);
        }
        #endregion

        #region 刷新照片集合
        /// <summary>
        /// 刷新照片集合
        /// </summary>
        public void RefreshPhoto()
        {
            DataEntites.Refresh(System.Data.Objects.RefreshMode.StoreWins, DataEntites.photoInfo);
        }
        #endregion

        #region 根据指定的photoId获取photoInfo
        /// <summary>
        /// 根据指定的photoId获取photoInfo
        /// </summary>
        /// <param name="photoId"></param>
        /// <returns></returns>
        public photoInfo GetPhotoInfoByPhotoId(int photoId)
        {
            try
            {
                photoInfo photo = DataEntites.photoInfo.Where(p => p.photoId == photoId).FirstOrDefault();
                return photo;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        //--------------传统模式----------------
        /// <summary>
        /// 分配打印机
        /// </summary>
        public int DistributeSinglePhoto(MODEL.DigitalModel.STDistributePhoto pi, int printerDPI, int techId, int userId)
        {
            con.ConnectionString = conStr;
            SqlCommand cmd = new SqlCommand();

            //参数定义
            string checkSql = "select case when status=1 then 1 when status<>1 then 0 end from orderinfo where orderproductid=" + pi.OrderProductID;
            string updateSql = "update photoinfo set";                                //update语句
            string updateSql2 = "";
            string selectSql = "select TotalNum,ProductNum from photoInfo,orderinfo where photoid=" + pi.PhotoID + " and photoinfo.orderproductid=orderinfo.orderproductid";
            string selectSql2 = "select * from photoinfo where photoid=" + pi.PhotoID;
            //select语句
            string insertSql = "insert into photoInfo(OrderProductId,PhotoBarCode,photoName,Height,Width,pixWidth,pixHeight,paperTypeID,paperFaceId,picPath,OldPicPath,Remark,IsModifySize,printerId,status,TotalNum,MakeUpNum)";
            //insert语句(插入重复的照片)
            int insertNum = 0;                                                  //重复的照片数量
            MODEL.DigitalModel.PhotoInfoSame photo = new MINERP.MODEL.DigitalModel.PhotoInfoSame();   //要分配的照片

            try
            {
                SqlTransaction tran;
                cmd.Connection = con;
                con.Open();
                tran = con.BeginTransaction();
                try
                {
                    cmd.Connection = con;
                    cmd.Transaction = tran;

                    //检查产品是否处于可执行状态(orderInfo.Status=1)
                    cmd.CommandText = checkSql;
                    int canDo = Convert.ToInt32(cmd.ExecuteScalar());
                    if (canDo == 0)
                    {
                        tran.Commit();
                        return 0;
                    }

                    if (pi.PhotoDPI != printerDPI && pi.DistributeType == true)         //按打印机DPI分配，并且照片DPI不等于打印机DPI
                    {
                        updateSql += " Height=round(cast(pixHeight as decimal)/" + printerDPI + ",1),Width=round(cast(pixWidth as decimal)/" + printerDPI + ",1),pixHeight=cast(round(round(cast(pixHeight as decimal)/" + printerDPI + ",1)*" + printerDPI + ",0) as int),pixWidth=cast(round(round(cast(pixWidth as decimal)/" + printerDPI + ",1)*" + printerDPI + ",0) as int),";
                    }
                    else if (pi.PhotoDPI != printerDPI && pi.DistributeType == false)   //按照片本身尺寸分配
                    {
                        updateSql += " Height=" + pi.Height + ",Width=" + pi.Width + ",pixHeight=cast(round(" + pi.Height * printerDPI + ",0) as int),pixWidth=cast(round(" + pi.Width * printerDPI + ",0) as int),";
                    }
                    else
                    {
                        updateSql += " Height=" + pi.Height + ",Width=" + pi.Width + ",pixHeight=cast(round(" + pi.Height * pi.PhotoDPI + ",0) as int),pixWidth=cast(round(" + pi.Width * pi.PhotoDPI + ",0) as int),";
                    }
                    int distributed = (int)COM.PhotoStatus.DistributedPrinter;
                    updateSql += " status=" + distributed + ",printerId=" + pi.PrinterID;
                    updateSql += " where photoid=" + pi.PhotoID;
                    cmd.CommandText = updateSql;
                    cmd.ExecuteNonQuery();                      //修改照片本身属性

                    cmd.CommandText = selectSql;
                    SqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        insertNum = Convert.ToInt32(reader["TotalNum"]) * Convert.ToInt32(reader["ProductNum"]) - 1;
                    }
                    reader.Close();

                    updateSql2 = " update photoinfo set totalNum=1 where photoid=" + pi.PhotoID;
                    cmd.CommandText = updateSql2;
                    cmd.ExecuteNonQuery();

                    if (insertNum > 0)                          //插入重复照片
                    {
                        cmd.CommandText = selectSql2;
                        reader = cmd.ExecuteReader();
                        while (reader.Read())
                        {
                            photo.Height = Convert.ToDouble(reader["Height"]);
                            photo.Width = Convert.ToDouble(reader["Width"]);
                            photo.IsModifySize = Convert.ToInt16(reader["IsModifySize"]);
                            if (reader["MakeUpNum"] != DBNull.Value)
                                photo.MakeUpNum = Convert.ToInt32(reader["MakeUpNum"]);
                            photo.OldPicPath = reader["OldPicPath"].ToString();
                            photo.OrderProductId = Convert.ToInt32(reader["OrderProductId"]);
                            photo.PaperFaceId = Convert.ToInt32(reader["PaperFaceId"]);
                            photo.PaperTypeID = Convert.ToInt32(reader["PaperTypeID"]);
                            photo.PhotoBarCode = reader["PhotoBarCode"].ToString();
                            photo.PhotoId = Convert.ToInt32(reader["PhotoId"]);
                            photo.photoName = reader["photoName"].ToString();
                            photo.PicPath = reader["PicPath"].ToString();
                            photo.PixHeight = Convert.ToInt32(reader["PixHeight"]);
                            photo.PixWidth = Convert.ToInt32(reader["PixWidth"]);
                            photo.PrinterId = Convert.ToInt32(reader["PrinterId"]);
                            photo.Remark = reader["Remark"].ToString();
                            photo.Status = Convert.ToInt32(reader["Status"]);
                            photo.TotalNum = Convert.ToInt32(reader["TotalNum"]);
                            //photo.UserId=Convert.ToInt32(reader["UserId"]);
                        }
                        reader.Close();

                        //重复照片
                        for (int i = 0; i < insertNum; i++)
                        {
                            string insertSql2 = "";
                            insertSql2 = insertSql + " values(" + pi.OrderProductID + ",'3333333333','" + photo.photoName + "'," + photo.Height + "," + photo.Width + "," + photo.PixWidth + "," + photo.PixHeight + "," + photo.PaperTypeID + "," + photo.PaperFaceId + ",'" + photo.PicPath + "','" + photo.OldPicPath + "','" + photo.Remark + "'," + photo.IsModifySize + "," + photo.PrinterId + "," + photo.Status + "," + photo.TotalNum + "," + photo.MakeUpNum + ")";
                            cmd.CommandText = insertSql2;
                            cmd.ExecuteNonQuery();

                            selectSql = "select @@identity";
                            cmd.CommandText = selectSql;
                            int currentPhotoId = Convert.ToInt32(cmd.ExecuteScalar());

                            string photoBarCode = "3" + string.Format("{0:d9}", currentPhotoId);
                            updateSql2 = "update photoInfo set photobarcode='" + photoBarCode + "' where photoid=" + currentPhotoId;
                            cmd.CommandText = updateSql2;
                            cmd.ExecuteNonQuery();
                        }
                    }

                    //修改产品流程...
                    int noDistributed = (int)COM.PhotoStatus.NoDistributePrinter;
                    string selectSql3 = "select count(photoId) from photoInfo where orderproductid=" + pi.OrderProductID + " and status=" + noDistributed;
                    cmd.CommandText = selectSql3;
                    int noDistributedNum = Convert.ToInt32(cmd.ExecuteScalar());
                    if (noDistributedNum == 0)
                    {
                        DateTime completeTime = DateTime.Now;
                        int completed = (int)COM.OrderFlowListStatus.Complete;
                        int doing = (int)COM.OrderFlowListStatus.Useable;
                        string selectSql4 = "select top 1 techid from workorderflowlist where orderproductid=" + pi.OrderProductID + " and techid>" + techId + " order by techid";
                        cmd.CommandText = selectSql4;
                        int nextTech = Convert.ToInt32(cmd.ExecuteScalar());
                        string updateSql3 = "update workorderflowlist set status=case when techid=" + techId + " then " + completed + " when techid=" + nextTech + " then " + doing + " end,CompletedTime='" + completeTime + "' where orderproductid=" + pi.OrderProductID + " and techid in (" + techId + "," + nextTech + ")";
                        cmd.CommandText = updateSql3;
                        cmd.ExecuteNonQuery();
                    }

                    tran.Commit();
                    return insertNum + 1;
                }
                catch (Exception exx)
                {
                    tran.Rollback();
                    throw exx;
                }
                finally
                {
                    con.Close();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 设置打印机属性
        /// </summary>
        public void SetPrinterAttribute(int printerId, double length, double width, double speed, int dpi, bool disable)
        {
            try
            {
                int u = 0;
                if (disable)
                    u = 1;
                else
                    u = 0;
                string sql = "update printer set plength=" + length + ",pwidth=" + width + ",speed=" + speed + ",pdpi=" + dpi + ",status3=" + u + " where PrinterID=" + printerId;
                using (con = new SqlConnection(conStr))
                {
                    SqlCommand cmd = new SqlCommand(sql, con);
                    con.Open();
                    cmd.ExecuteNonQuery();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #region 获取打印机现有的任务量
        /// <summary>
        /// 获取打印机现有的任务量
        /// </summary>
        /// <param name="printerId"></param>
        /// <returns></returns>
        public double GetTask(int printerId)
        {
            try
            {
                int distributed = (int)COM.PhotoStatus.DistributedPrinter;
                int pinBan = (int)COM.PhotoStatus.PingBan;
                double task = 0;
                string sql = "select sum(height*2.54*width*2.54/10000) where (status=" + distributed + " or status=" + pinBan + ") and printerId=" + printerId;
                using (con = new SqlConnection(conStr))
                {
                    SqlCommand cmd = new SqlCommand(sql, con);
                    con.Open();
                    object r = cmd.ExecuteScalar();
                    if (r != DBNull.Value)
                    {
                        task = Convert.ToDouble(r);
                    }
                }
                return task;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public DataTable AutoDistributePrinter(int inUndisphotoStatus, int inOrderinfostatus, int inTechid, int inDisphotoStatus, int inUserId, out int intSuccessNum)
        {
            try
            {


                using (con = new SqlConnection(conStr))
                {
                    SqlCommand cmd = new SqlCommand();

                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Connection = con;
                    cmd.CommandText = "Proce_AutoDistributePrinter";
                    cmd.Parameters.Add("@undisphotoStatus", SqlDbType.Int);
                    cmd.Parameters["@undisphotoStatus"].Value = inUndisphotoStatus;
                    cmd.Parameters.Add("@orderinfostatus", SqlDbType.Int);
                    cmd.Parameters["@orderinfostatus"].Value = inOrderinfostatus;
                    cmd.Parameters.Add("@techid", SqlDbType.Int );
                    cmd.Parameters["@techid"].Value = inTechid;
                    cmd.Parameters.Add("@disphotoStatus", SqlDbType.Int);
                    cmd.Parameters["@disphotoStatus"].Value = inDisphotoStatus;
                    cmd.Parameters.Add("@userid", SqlDbType.Int);
                    cmd.Parameters["@userid"].Value = inUserId;
                    cmd.Parameters.Add("@OutdisphotoCount", SqlDbType.Decimal).Direction = ParameterDirection.Output;
                    con.Open();
                    SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
                    sqlDataAdapter.SelectCommand = cmd;
                    DataSet dataSet = new DataSet();
                    SqlCommandBuilder sqlCommandBuilder = new SqlCommandBuilder(sqlDataAdapter);
                    sqlDataAdapter.Fill(dataSet, "unDistributeList");
                    intSuccessNum = Convert.ToInt32(cmd.Parameters["@OutdisphotoCount"].Value);

                    return dataSet.Tables[0];
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        #endregion
    }
}
